package com.LiL.Wayne.Activity.activity;

import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.LiL.Wayne.Activity.R;
import com.LiL.Wayne.Activity.R.anim;
import com.LiL.Wayne.Activity.R.drawable;
import com.LiL.Wayne.Activity.R.id;
import com.LiL.Wayne.Activity.R.layout;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.ImageAdapter;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.SharePm;
import com.LiL.Wayne.Activity.activity.PlayerVideoLyrics.ViewHolder;
import com.audamob.audasingers.model.Song;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Lyrics_Interface extends Activity {

	String Lyrics = "";
	String SongName = "";
	String Album = "";
	long Duration;

	String iframe = "";

	Boolean PopUpOnshare = false;
	PopupWindow PopUpShare;
	Activity activity;

	class SharePm {
		String Name;
		Drawable d;
		ResolveInfo ResolveInfo;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_activity_lyrics_interface);
		Bundle b = getIntent().getExtras();
		SongName = b.getString("name");
		Album = b.getString("album");
		activity = this;

		// revmob.showFullscreen(this);
		TextView namesong = (TextView) findViewById(R.id.NameSong);
		namesong.setText("Lyrics : " + SongName);
		ImageView share = (ImageView) findViewById(R.id.Share);
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View vv) {
				// TODO Auto-generated method stub

				if (!PopUpOnshare) {
					PopUpOnshare = true;
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View v = vi.inflate(R.layout.dialog_options_share, null);
					PopUpShare = new PopupWindow(v, 500, 500);
					PopUpShare.setOutsideTouchable(false);
					PopUpShare.showAsDropDown(activity.findViewById(R.id.Share));
					ArrayList<SharePm> ListSHare = new ArrayList<SharePm>();
					ListView lv = (ListView) v.findViewById(R.id.ListShare);
					String mimeType = null;
					mimeType = "text/plain";
					Intent shareIntent = new Intent(
							android.content.Intent.ACTION_SEND);
					shareIntent.setType(mimeType);

					shareIntent.putExtra(Intent.EXTRA_TEXT, "");
					shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

					final PackageManager pm = v.getContext()
							.getPackageManager();
					final List<ResolveInfo> activityList = pm
							.queryIntentActivities(shareIntent, 0);
					for (final ResolveInfo app : activityList) {
						SharePm sp = new SharePm();
						sp.d = app.loadIcon(pm);
						sp.Name = app.loadLabel(pm).toString();
						sp.ResolveInfo = app;
						ListSHare.add(sp);
						Log.d("ShareShare", " " + app.loadLabel(pm).toString());
					}
					count = ListSHare.size();
					String nom = "aymennnnn";// ImageList.get(currentIndex).getNewLocation();
					String Nomold = "zvzdv";// ImageList.get(currentIndex).getOldLocation();
					// Nomold=Nomold.substring(Nomold.lastIndexOf("."),
					// Nomold.length());

					lv.setAdapter(new ImageAdapter(ListSHare));

				} else {
					PopUpShare.dismiss();
					PopUpOnshare = false;

				}
			}
		});

		ThreadLoad threadLoad = new ThreadLoad(handlerLoad);
		threadLoad.start();
		UpdaterProgressThread p = new UpdaterProgressThread(progressHandler);
		p.start();

	}

	int compteur = 0;
	private Handler progressHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (compteur == 0) {
				if (Build.VERSION.SDK_INT >= 16) {
					((ImageView) findViewById(R.id.Progress))
							.setBackground(getResources().getDrawable(
									R.drawable.progres1));

				} else {

					((ImageView) findViewById(R.id.Progress))
							.setBackgroundDrawable(getResources().getDrawable(
									R.drawable.progres1));
				}

				compteur = 1;
			} else if (compteur == 1) {
				if (Build.VERSION.SDK_INT >= 16) {
					((ImageView) findViewById(R.id.Progress))
							.setBackground(getResources().getDrawable(
									R.drawable.progres2));

				} else {

					((ImageView) findViewById(R.id.Progress))
							.setBackgroundDrawable(getResources().getDrawable(
									R.drawable.progres2));
				}

				compteur = 2;
			} else {
				if (Build.VERSION.SDK_INT >= 16) {
					((ImageView) findViewById(R.id.Progress))
							.setBackground(getResources().getDrawable(
									R.drawable.progres3));

				} else {

					((ImageView) findViewById(R.id.Progress))
							.setBackgroundDrawable(getResources().getDrawable(
									R.drawable.progres3));
				}

				compteur = 0;
			}

			super.handleMessage(msg);
		}
	};
	Boolean Done = false;

	class UpdaterProgressThread extends Thread {
		final static int DONE = 0;
		final static int RUNNING = 1;
		final static int ECOUTE = 2;
		Handler mHandler;
		int mState;
		int total;
		int delay = 1000;
		int tranlationstate;

		public UpdaterProgressThread(Handler h) {
			// TODO Auto-generated constructor stub

			mHandler = h;
		}

		public void run() {
			mState = RUNNING;
			while (!Done) {
				try {
					currentThread().sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(5);
			}

		}

		public void setState(int state) {
			mState = state;
		}
	}

	int count = 0;

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		ArrayList<SharePm> list;

		public ImageAdapter(ArrayList<SharePm> listSHare) {
			mInflater = (LayoutInflater) getBaseContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			list = listSHare;
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.item_share, null);

				holder.ImageFolder = (ImageView) convertView
						.findViewById(R.id.IconAPp);
				holder.NameFolder = (TextView) convertView
						.findViewById(R.id.namAPp);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int h = v.getId();
					startResolvedActivity(list.get(holder.id).ResolveInfo);
					// PopUpShare.dismiss();
					// PopUpOnshare=false;
					// hidecurrentImage();
				}
			});

			holder.ImageFolder.setId(position);
			holder.NameFolder.setId(position);

			int h = holder.ImageFolder.getId();

			holder.ImageFolder.setImageDrawable(list.get(h).d);

			holder.NameFolder.setText(list.get(h).Name);
			holder.id = position;
			return convertView;
		}
	}

	class ViewHolder {

		ImageView ImageFolder;
		TextView NameFolder;
		int id;

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (PopUpOnshare) {
			PopUpShare.dismiss();
			PopUpOnshare = false;
		} else {
			finish();
			overridePendingTransition(R.anim.push_down_out_back,
					R.anim.push_down_in_back);
		}
	}

	private void startResolvedActivity(ResolveInfo info) {

		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		String mimeType = null;
		mimeType = "text/plain";
		shareIntent.setType(mimeType);

		String nom = TextLyrics.getText().toString();// ImageList.get(currentIndex).getNewLocation();

		shareIntent.putExtra(Intent.EXTRA_TEXT, nom);
		shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		final Intent resolvedIntent = new Intent(shareIntent);
		ActivityInfo ai = info.activityInfo;

		resolvedIntent.setComponent(new ComponentName(
				ai.applicationInfo.packageName, ai.name));
		startActivity(resolvedIntent);

	}

	TextView TextLyrics;

	final Handler handlerLoad = new Handler() {

		public void handleMessage(Message msg) {
			try {
				TextLyrics = (TextView) findViewById(R.id.TextLyrics);
				String lyric = msg.getData().toString();
				String cast = "Bundle[{url=";

				lyric = lyric.substring(cast.length() + 1, lyric.length() - 3);

				TextLyrics.setText(lyric);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Done = true;
			((ImageView) findViewById(R.id.Progress)).setVisibility(View.GONE);
		}
	};

	private class ThreadLoad extends Thread {
		Handler mHandler;

		ThreadLoad(Handler h) {
			mHandler = h;
		}

		public void run() {
			try {
				currentThread().sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String UrlBack = "";
			try {

				String SongNamee = SongName.replace(" ", "_");

				String UrlLyrics = "http://lyrics.wikia.com/Lil_Wayne:"
						+ SongNamee;
				org.jsoup.nodes.Document doc = Jsoup.connect(UrlLyrics).get();
				Elements content = doc.getElementsByTag("div");
				// Elements links = content.getElementsByTag("a");
				for (Element link : content) {
					String linkHref = link.className();
					if (linkHref.equals("lyricbox")) {
						Log.d("Lyrics", "lyrics= " + linkHref);
						String linkText = link.text();
						try {
							linkText = linkText.substring(0,
									linkText.lastIndexOf("Send "));
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							linkText = linkText.substring(0,
									linkText.lastIndexOf("</lyrics> "));
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							linkText = linkText.substring(
									linkText.indexOf("to your Cell") + 12,
									linkText.length());
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							linkText = linkText
									.substring(0, linkText
											.lastIndexOf("we are not licensed"));
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							linkText = linkText.replace(",", "\n\n");
						} catch (Exception e) {
							// TODO: handle exception
						}
						UrlBack = linkText;

					}
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("url", "" + UrlBack);
			msg.setData(b);
			mHandler.sendMessage(msg);

		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// link.open();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		super.onDestroy();
	}

	boolean displayed = false;

}
